<template>
  <el-form inline>
    <el-form-item label="标签名" required>
      <el-input v-model="tagName" clearable/>
    </el-form-item>
    <el-form-item>
      <el-button @click="onAdd()">添加根标签</el-button>
    </el-form-item>
  </el-form>
  <el-tree default-expand-all :data="tree.children" :props="defaultProps" @node-click="handleNodeClick"
           :expand-on-click-node="false">
    <template #default="{node,data}">
      <span class="custom-tree-node">
        <span>{{ node.label }}</span>
        <span>
            <a @click="onAdd(data)">添加</a>
            <a style="margin-left: 8px" @click="onRemove(node, data)">删除</a>
          </span>
      </span>
    </template>
  </el-tree>
</template>

<script lang="ts" setup>
import type Node from 'element-plus/es/components/tree/src/model/node'

interface Tree {
  label: string
  children?: Tree[]
}

const defaultProps = {
  children: 'children',
  label: 'label',
}

const tagName = ref<string>();
const tree = ref<Tree>({
  label: '',
  children: [
    {label: 'test', children: []}
  ]
});

const handleNodeClick = (data: Tree) => {
  console.log(data)
}

const onAdd = (target = tree.value) => {
  if (tagName.value) {
    const children = target.children!;
    const exist = children.some(value => value.label === tagName.value);
    if (!exist) {
      children.push({
        label: tagName.value,
        children: []
      })
      tagName.value = '';
    }
  }
}

const onRemove = (node: Node, data: Tree) => {
  const parent = node.parent
  const children: Tree[] = parent.data.children || parent.data
  const index = children.findIndex((d) => d.label === data.label)
  children.splice(index, 1)
}

</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
